package com.test.webchat.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.webchat.Mapper.MessageMapper;
import com.test.webchat.Mapper.MessageSessionUserMapper;
import com.test.webchat.Pojo.Model.Friend;
import com.test.webchat.Pojo.Model.Message;
import com.test.webchat.Pojo.Model.MessageSession;
import com.test.webchat.Pojo.Response.MessageSessionResponse;
import com.test.webchat.Service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SessionServiceImpl implements SessionService {
    @Autowired
    private MessageSessionUserMapper messageSessionUserMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public List<Integer> getAllSessionId(Integer userId) {
        return messageSessionUserMapper.getSessionIdsByUserId(userId);
    }

    @Override
    public List<Friend> getFriendsBySessionId(Integer sessionId, Integer userId) {
        return messageSessionUserMapper.getFriendsBySessionId(sessionId, userId);
    }

    @Override
    public List<MessageSessionResponse> getSessionList(Integer userId) {
        List<MessageSessionResponse> ret = new ArrayList<>();
        List<Integer> allSessionId = getAllSessionId(userId);
        for (Integer sessionId : allSessionId) {
            List<Friend> friends = getFriendsBySessionId(sessionId, userId);
            log.info("friends为：{}", friends);

            String lastMessage = messageMapper.getLastMassage(sessionId);
            if(lastMessage==null){
                lastMessage = "";
            }
            MessageSessionResponse messageSession = new MessageSessionResponse(sessionId, friends, lastMessage);
            ret.add(messageSession);
        }
        return ret;
    }

    @Override
    @Transactional
    public Integer addSession(Integer toUserId, Integer userId) {
        MessageSession messageSession = new MessageSession();
        Integer index = null;
        try {
            index = messageSessionUserMapper.addSession(messageSession);
            if (index == 1) {
                messageSessionUserMapper.addUserToSession(messageSession.getSessionId(), toUserId);
                messageSessionUserMapper.addUserToSession(messageSession.getSessionId(), userId);
                return messageSession.getSessionId();
            }
            return null;
        } catch (Exception e) {
            log.info("新增会话失败...");
            return null;
        }

    }
}
